<?php
/**
 *
 */
class panel__rrp__commands_executor
	extends panel__rrp {

	public function __route() {

		return array(

			"get_preexecution_data" => TRUE,
			"execute_command" => TRUE,

		);

	}	# Function

	public function execute_command( array $_ ) {


		$vendor = panel__model__vendors::getVendor(
			p_defined($_["vendor_id"], "Vendor ID"),
			array("exception_if_not_exists" => 2)
		);

		$devices = panel__model__devices::getDevices( array(

			"select_ip" => TRUE,

			"where_id_in"     => p()->validate($_["devices"], "array!", "Devices"),
			"where_vendor_id" => $vendor["eid"]

		) );

		if( !count($devices) ) {

			$e = new panel__e__validation();
			$e->replaceMessage("No vendor devices found");

		}	# if

		$command = panel__model__commands::getCommand(
			p_defined($_["command_id"]),
			array("where_vendor_id" => $vendor["eid"])
		);

		$R = array(

			"output" => array()

		);

		$R["output"][] = "Executed commands: " . $command["command"] . "\n\n\n";

		foreach( $devices as $_device ) {

			$_rancid = panel__settings__environment::getRancidCommand();

			$_rancid = str_replace("{ip}", $_device["ip"], $_rancid);
			$_rancid = str_replace("{command}", escapeshellarg($command["command"]), $_rancid );
			$_rancid = str_replace("{vendor}", $vendor["title"], $_rancid);

			$_output = "";

			exec($_rancid, $_output, $_return);


			$R["output"][] = "Machine ({$vendor["title"]}), IP: {$_device["ip"]}:\n\n";
			$R["output"][] = implode("\n", $_output);
			$R["output"][] = "Return code: " . $_return;

		}	# foreach

		$R["output"] = implode("\n", $R["output"]);

		return $R;

	}	# Function

	public function get_preexecution_data( array $_ ) {

		$vendor = panel__model__vendors::getVendor(
			p_defined($_["vendor_id"], "Vendor ID"),
			array("exception_if_not_exists" => 2)
		);

		$devices = panel__model__devices::getDevices( array(

			"select_ip" => TRUE,

			"where_id_in"     => p()->validate($_["devices"], "array!", "Devices"),
			"where_vendor_id" => $vendor["eid"]

		) );

		if( !count($devices) ) {

			$e = new panel__e__validation();
			$e->replaceMessage("No vendor devices found");

		}	# if

		$commands = panel__model__commands::getCommands( array( "where_vendor_id" => $vendor["eid"] ) );

		if( !count($commands) ) {

			$e = new panel__e__validation();
			$e->replaceMessage("No vendor commands found");

		}	# if

		return array(

			"devices"  => $devices,
			"vendor"   => $vendor,
			"commands" => $commands

		);

	}	# Function

}	# Class

/* EOF */